package com.example.service.impl;

import com.example.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class SendMailServiceImpl implements SendMailService {

    @Autowired
    private JavaMailSender javaMailSender;

    //发送人
    private String from = "17633540265@sina.cn";
    //接收人
    private String to = "1755140651@qq.com";
    //标题
    private String subject = "测试邮件";
    //正文
    private String context = "<a href='https://www.itcast.cn'>点开有惊喜</a>";

    @Override
    public void sendMail() {
        //发送简单email
       /* SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from + "(小甜甜)");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);*/

        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(from + "(小甜甜)");
            helper.setTo(to);
            helper.setSubject(subject);
            //发送带html的email
            helper.setText(context,true);
            //添加附件
            File file = new File("D:\\IdeaProjects\\springboot\\springboot_23_mail\\src\\main\\resources\\application.yml");
            helper.addAttachment(file.getName(),file);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
